#coding:utf-8
__author__="Rafael Santos (@tucif)"
__date__ ="$18/04/2009 03:56:35 PM$"

import pygtk
pygtk.require('2.0')
import gtk

import twirexConnection
import gobject
import hashlib

#Varios (Pasar a utils)
def showInfoDialog(message,parentWindow,closeOperation):
        info = gtk.Dialog(title=message, parent=parentWindow, buttons=(gtk.STOCK_OK, gtk.RESPONSE_CLOSE))
        info.get_child().pack_start(gtk.Label(message))
        info.connect("response",closeOperation)
        info.show_all()

def closeDialog(widget,response):
    widget.destroy()

class TwirexGUI():
    def __init__(self, grrList):
        self.tags = ""#",".join(grrList[0].tags)
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("Grr-it!")
        self.window.set_size_request(300, 650)#625
        self.window.connect("delete_event", gtk.main_quit)

        #ACCOUNT SETTINGS:
        self.accountSettings = AccountSettingsDialog(self.window)
        #TIMER
        self.updateTimer = gobject.timeout_add(1000*30,self.updateWindow)
        
        self.mainBox = gtk.VBox(False,0)
        self.mainBox.set_size_request(280, 490)

        self.scrolledArea = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
        self.scrolledArea.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
        self.scrolledArea.set_border_width(10)
        self.scrolledArea.set_size_request(280, 490)

        self.grrBox = gtk.VBox(False,0)
        self.grrBox.set_size_request(250, max(len(grrList)*85,460))
        self.scrolledArea.add_with_viewport(self.grrBox)
        
        self.canShrink = 490/len(grrList)*85 >1

        self.addGrrs(grrList)

        ##Upper info panel
        self.upperInfoPanel = gtk.HBox(False,0)
        self.upperInfoPanel.set_size_request(280,25)
        self.lblCurrentTags = gtk.Label("Showing: %s"%(self.tags if self.tags else "-All tags-"))
        self.buttonHome = gtk.Button("Show All")
        self.buttonHome.connect('clicked',self.changeTags,None)

        self.upperInfoPanel.pack_start(self.buttonHome,False,False)
        self.upperInfoPanel.pack_start(self.lblCurrentTags,False,False)

        self.mainBox.pack_start(self.upperInfoPanel,False,False)
        self.mainBox.pack_start(self.scrolledArea,False,False)

        self.tagsInput = gtk.HBox(False,0)
        self.lblTags = gtk.Label('Tags: ')
        self.tagsBox= gtk.Entry()
        #self.tagsBox.set_text(",".join(grrList[0].tags))
        self.tagsBox.set_text("")
        self.buttonTags = gtk.Button('refresh')
        self.buttonTags.connect('clicked',self.changeTags,self.tagsBox)
        self.tagsInput.pack_start(self.lblTags,False,False)
        self.tagsInput.pack_start(self.tagsBox,True,True)
        self.tagsInput.pack_start(self.buttonTags,False,False)
        
        self.mainBox.pack_start(self.tagsInput,False,True)

        self.grrInput =gtk.HBox(False,0)
        self.lblGrr = gtk.Label('Grr: ')
        self.txtGrr = gtk.TextView()
        self.txtGrr.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        self.txtGrr.set_size_request(250,85)
        self.buttonGrr = gtk.Button('Send')
        self.buttonGrr.connect('clicked',self.postGrr,self.txtGrr)

        self.grrInput.pack_start(self.lblGrr,False,False)
        self.grrInput.pack_start(self.txtGrr,True,True)
        self.grrInput.pack_start(self.buttonGrr,False,False)

        self.mainBox.pack_start(self.grrInput,False,True)

        self.buttonSettings = gtk.Button('Settings')
        self.buttonSettings.connect('clicked',self.showSettings)
        self.buttonSettings.set_size_request(20,25)
        self.mainBox.pack_start(self.buttonSettings,False,False)

        self.window.add(self.mainBox)
        self.window.show_all()
    

    def updateWindow(self):
        self.changeTags(None,tagsBox=self.tagsBox)

    def changeTags(self,button,tagsBox=None,tags=""):
        #buff = tagsBox.get_buffer()
        #start = buff.get_start_iter()
        #end = buff.get_end_iter()
        #tags = tagsBox.get_buffer().get_text(start,end)
        if tagsBox:
            tags = tagsBox.get_text()
            tags.replace('/',',')
        grrList = twirexConnection.make_request(tags)
        self.addGrrs(grrList)
        self.tags = tags
        self.lblCurrentTags.set_text("Showing: %s"%(self.tags if self.tags else "-All tags-"))
        self.tagsBox.set_text(tags)
        self.scrolledArea.set_vadjustment(gtk.Adjustment())
        
    def postGrr(self,button,grrBox):
        buff = grrBox.get_buffer()
        start = buff.get_start_iter()
        end = buff.get_end_iter()
        grr = grrBox.get_buffer().get_text(start,end)
        grr = unicode(grr)
        print grr
        tags = self.tagsBox.get_text()
        if len(grr) > 140 or len(grr) == 0 :
            message = "Not valid"
            return None #should have a status bar..
        else:
            message="Success"
        usrData=self.accountSettings.load_settings()
        response = None
        if usrData:
            response = twirexConnection.make_post(usrData[0], usrData[1], grr, tags)
        else:
            message = "Account Settings Wrong"
        if response:
            if response.startswith("bad"):
                message = "Wrong username or password."
                showInfoDialog(message,self.window,closeDialog)
            grrBox.get_buffer().set_text("")
            self.changeTags(button, self.tagsBox)
            
      
            
    def addGrrs(self, grrList):
        for child in self.grrBox.get_children():
            self.grrBox.remove(child)
            
        for grr in grrList:
            ##Cada grr debera ser un HBox para que pueda ponerse la imagen al lado y abajo fecha y demas
            grrWrapper = gtk.VBox(False,0)
            grrContainer = gtk.HBox(False,0)
            txt = gtk.TextView()
            txt.set_editable(False)
            txt.set_cursor_visible(False)
            txt.set_wrap_mode(gtk.WRAP_WORD)
            txt.set_justification(gtk.JUSTIFY_LEFT)
            txt.get_buffer().set_text(unicode(grr))
            txt.set_border_width(5)
            txt.set_size_request(200,85)
            img = gtk.Image()
            img.set_from_file(grr.image)
            grrContainer.pack_start(img,False,False)
            grrContainer.pack_start(txt,False,False)

            grrMeta = gtk.HBox(False,0)


            lblDateTime = gtk.Label('%s at %s'%(grr.date,grr.time))
            buttonGrrTags = gtk.Button(",".join(grr.tags))
            buttonGrrTags.connect('clicked',self.changeTags,None,",".join(grr.tags))
            buttonReply = gtk.Button('->')
            buttonReply.connect('clicked',self.replyUser,grr)
            buttonReply.set_size_request(30,20)

            grrMeta.pack_start(lblDateTime,False,False)
            grrMeta.pack_start(buttonGrrTags,False,False)
            grrMeta.pack_start(buttonReply,False,False)

            grrWrapper.pack_start(grrContainer,False,False)
            grrWrapper.pack_start(grrMeta,False,False)
            
            self.grrBox.pack_start(grrWrapper,False,False)
            
        self.grrBox.show_all()

    def showSettings(self,widget):
        self.accountSettings = AccountSettingsDialog(self.window)
        self.accountSettings.show()

    def replyUser(self,widget, grr):
        self.tagsBox.set_text(",".join(grr.tags))
        self.txtGrr.get_buffer().set_text('@%s '%(grr.user))
        self.txtGrr.grab_focus()

class AccountSettingsDialog():
    def __init__(self, parentWindow):
        self.dialog = gtk.Dialog(title="Twirex Account Settings",
                            parent=parentWindow,flags=gtk.DIALOG_MODAL,
                            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                             gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        self.dialog.connect("response",self.save_settings)
        self.parentWindow = parentWindow
        #self.connect("delete_event", self.hide_all)
        
        self.mainBox = self.dialog.get_child()
#        self.mainBox.set_size_request(280, 490)

        self.lblUser = gtk.Label('Username:')
        self.userEntry = gtk.Entry(max=30)

        self.lblPword = gtk.Label('Password:')
        self.pwordEntry = gtk.Entry(max=30)
        self.pwordEntry.set_editable(True)
        self.pwordEntry.set_visibility(False)

        self.mainBox.pack_start(self.lblUser, False, False, 0)
        self.mainBox.pack_start(self.userEntry, False, False, 0)
        self.mainBox.pack_start(self.lblPword, False, False, 0)
        self.mainBox.pack_start(self.pwordEntry, False, False, 0)

        usrData = self.load_settings()
        if usrData:
            self.userEntry.set_text(usrData[0])
            #self.pwordEntry.set_text(usrData[1])
            self.pwordEntry.set_text("")
        else:
            self.dialog.show_all()

    def save_settings(self, dialog, response):
        if response == gtk.RESPONSE_REJECT:
            self.dialog.hide_all()
        elif response== gtk.RESPONSE_ACCEPT:
            usr = self.userEntry.get_text()
            md5pwd = hashlib.md5()
            pwd = self.pwordEntry.get_text()
            md5pwd.update(pwd)
            f = open ('./res/grr-it.settings','wb')
            f.write("%s\n"%(usr))
            f.write(md5pwd.hexdigest())
            f.close()
            self.dialog.hide_all()
            self.login_user()
 
        self.dialog.destroy()
        
    def load_settings(self):
        try:
            f = open ('./res/grr-it.settings','rb')
            usr = f.readline()[:-1]#eliminar \n
            pwd = f.readline()
            f.close()
            return [usr,pwd]
        except:
            return None
        
    def show(self):
        self.dialog.show_all()

    def login_user(self):
        [usr,pwd]=self.load_settings()
        validUser = twirexConnection.login(usr, pwd)
        if validUser != "(1)":
            showInfoDialog("Wrong username or password.",self.parentWindow,closeDialog)


